package cn.itsource.system.service.impl;

import cn.itsource.base.service.impl.BaseServiceImpl;
import cn.itsource.base.util.AjaxResult;
import cn.itsource.base.util.ErrorCode;
import cn.itsource.base.util.PageList;
import cn.itsource.global.exception.BusinessException;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.query.MenuQuery;
import cn.itsource.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper mapper;

    @Override
    public void deleteById(Long id) {
        Integer count = mapper.selectByPid(id);
        if(count > 0){
            throw new BusinessException(ErrorCode.BUSINESS_MENU_SUBORDINATE_ERROR.getCode());
        }
        super.deleteById(id);
    }

    @Override
    public PageList<Menu> queryPage(MenuQuery query) {
        if(query.getCurrentPage() < 1){
            throw new RuntimeException("");
        }
        //分页查询
        List<Menu> menus = super.query(query);
        //创建分页接收对象
        PageList<Menu> pageList = new PageList();
        //设置分页数据
        pageList.setData(menus);
        //设置分页总条数
        pageList.setCount(mapper.queryCount(query));
        return pageList;
    }

    @Override
    public AjaxResult getMenuTree() {
        List<Menu> departments = mapper.selectAll();//从数据库里面查询全部
        return AjaxResult.me().setResultObj(getMenuTree1(departments));
    }

    @Override
    public List<Long> selectIds(List<Long> ids) {
        return mapper.selectIds(ids);
    }

    @Override
    public List<Menu> selectMenu(List<Long> ids) {
        return mapper.selectMenu(ids);
    }

    @Override
    public List<Menu> getMenuTree1(List<Menu> menus){
        //第一个步找顶层
        List<Menu> top = new ArrayList<>();
        Map<Long, Menu> map = menus.stream()
                .collect(Collectors.toMap(Menu::getId, item -> item, (Key1, key2) -> Key1));
        //collect 收集
        //Collectors java8提供的一些收集器
        //(Key1, key2) -> Key1)  map key 不允许重复

        menus.stream().filter(dept->{
            if(dept.getParentId() == null){
                top.add(dept);
                return false;
            }
            return true;
        }).forEach(detp->{
            //只要你不是顶层  你一定是某个人的儿子
            Long parentId = detp.getParentId();//爹的id
            Menu department1 = map.get(parentId);
            department1.getChildren().add(detp);//找到爹 把自己放进去
        });
        return top;
    }
}
